
import serial
import threading
import select
import redis
import time
from setting import ENABLE_ANTENNA_COMMAND, CABINET_CURRENT_RFID_READER_STATUS

import logging
logging.basicConfig(level = logging.INFO,format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

def singleton(cls): # 单例模式装饰器
    instance = None
    lock = threading.Lock()

    def get_instance(*args, **kwargs):
        nonlocal instance
        with lock:
            if not instance:
                instance = cls(*args, **kwargs)
            return instance
    return get_instance

@singleton
class RfidSerialPortMethod: # rfid串口方法

    def __enter__(self):

        return self

    def __exit__(self, exc_type, exc_val, exc_tb):

        self.ser.close()

    def __init__(self, serial_path="/dev/ttyS1", baud=115200):

        self.serial_path = serial_path

        self.ser = serial.Serial(self.serial_path, baud, 8, "N", timeout=0, stopbits=1)

        # self.receive_thread = threading.Thread(target=self.receive_data)

        # 创建一个Redis连接
        self.r = redis.Redis(host='localhost', port=6379, db=0)

        self.is_running = False

    def receive_data(self):

        self.is_running = True

        while self.is_running:

            if self.ser.in_waiting > 0:

                data = self.ser.read(self.ser.in_waiting)

                logger.info("receive_data: {}".format(data.hex()))

                self.r.rpush('rfid_reader_stack', data)

            select.select([self.ser], [], [], 0.1)

    def start_receive_thread(self):

        self.receive_thread.start()

    def stop_receive_thread(self):

        self.is_running = False

        self.receive_thread.join()

    # def send_data(self, data: str):

    #     logger.info("send: {}".format(data))

    #     self.ser.write(data.encode('utf-8'))

    def send_data(self, data: str):

        logger.info("send: {}".format(data))
        
        self.ser.write(bytes.fromhex(data))
    
    def stop_scan_rfid(self):

        send_times = 0

        while True:

            self.send_data("5A000102FF0000885A")

            self.r.set(CABINET_CURRENT_RFID_READER_STATUS, "下发暂停")

            time.sleep(1)

            back_info = self.r.get(CABINET_CURRENT_RFID_READER_STATUS)

            if back_info:

                back_info = back_info.decode()

                if back_info == "收到暂停":

                    break
            
            if send_times >= 2:

                self.r.set(CABINET_CURRENT_RFID_READER_STATUS, "读头异常")

            send_times += 1

    def scan_rfid(self):

        self.stop_scan_rfid()

        time.sleep(0.3)

        self.send_data(ENABLE_ANTENNA_COMMAND) 

        



if __name__ == "__main__":

    RfidSerialPortMethod().receive_data()

    # 在此之后，你可以继续调用发送数据的方法，而监听线程会在后台一直运行并处理接收到的数据



